<template>
  <div>
    <el-input v-model="name" disabled>
      <template slot="append">
        <el-button icon="el-icon-s-grid" @click="openModal" />
        <el-button icon="el-icon-delete" @click="clear" />
      </template>
    </el-input>

    <modal ref="modal" @ok="handleOK" />
  </div>
</template>

<script>
import modal from './singleSelectModal'
export default {
  name: 'ApiAppSingleSelect',
  components: {
    modal
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    width: {
      type: Number,
      default: 500,
      required: false
    },
    value: {
      type: String,
      default: '',
      required: false
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    // 绑定对象，用于父组件动态创建多个选择框的情况
    refObject: {
      type: Object,
      default: null,
      required: false
    }

  },
  data() {
    return {
      visible: false,
      name: ''
    }
  },
  watch: {
    value: {
      immediate: true,
      handler: 'handleValue'
    }
  },
  methods: {
    openModal() {
      this.$refs.modal.show(this.value, this.name)
    },
    handleValue() {
      if (this.value) {
        this.$api.cip.apiApp.get(this.value)
          .then((res) => {
            this.name = res.data.name
          })
      }
    },
    handleOK(id, name) {
      // 更新父组件绑定值
      this.$emit('change', id)
      // 将标识和名称传递回父组件
      this.$emit('changeSelect', id, name, this.refObject)
    },
    clear() {
      this.name = ''
      // 更新父组件绑定值
      this.$emit('change', null)
      // 将标识和名称传递回父组件
      this.$emit('changeSelect', '', '', this.refObject)
    }
  }
}
</script>

<style scoped>
</style>
